package org.example.utils;


import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 本地注册中心
 * @author: feixiang.li
 * @date: 2025-01-02 22:32
 */
@Slf4j
public class ServiceFactory {

    //保存所有有注解@RpcService的集合
    public static final Map<String, Object> serviceFactory = new ConcurrentHashMap<>();


    /**
     * 添加已注解的类进入工厂
     *
     * @param service     服务实体类
     * @param serviceName 服务名称
     * @param <T>         泛型
     */
    public <T> void addServiceProvider(T service, String serviceName) {
        if (serviceFactory.containsKey(serviceName)) {
            return;
        }
        serviceFactory.put(serviceName, service);
        log.info("服务类{}添加进工厂", serviceName);
    }

    /**
     * 远程调用接口从该方法获取
     *
     * @param serviceName 服务名称
     * @return 服务类
     */
    public Object getServiceProvider(String serviceName) {
        Object service = serviceFactory.get(serviceName);
        if (service == null) {
            throw new RuntimeException("未发现该服务");
        }
        return service;
    }
}
